package com.alex.monitor.core.alarm.impl;

import com.alex.monitor.core.properties.AlexMonitorProperties;
import com.alex.monitor.core.properties.AlexMonitorProperties.EmailConfig;
import com.alibaba.fastjson2.JSONObject;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;

/**
 * 基于邮件的报警器
 *
 * @author Alex.Liu
 * @date: 2025-02-16 15:38
 * @since 1.0.0
 */
@Slf4j
public class DefaultEmailMonitorAlarm extends AbstractMonitorAlarm {

    /**
     * 邮件配置
     */
    private final EmailConfig config;


    public DefaultEmailMonitorAlarm(AlexMonitorProperties properties) {
        super(properties);
        this.config = properties.getEmail();
    }

    @Override
    protected void doAlarm(String tag, JSONObject message) {
        // 配置邮件服务器属性
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", config.getHost());
        properties.put("mail.smtp.port", config.getPort());
        // 其他配置
        properties.putAll(config.getProperties());
        // 创建会话
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getUsername(), config.getPassword());
            }
        });
        try {
            // 收件人列表
            InternetAddress[] addresses = new InternetAddress[config.getTo().size()];
            for (int i = 0; i < config.getTo().size(); i++) {
                addresses[i] = new InternetAddress(config.getTo().get(i));
            }
            // 创建邮件消息
            Message mimeMessage = new MimeMessage(session);
            // 设置发件人
            mimeMessage.setFrom(new InternetAddress(config.getUsername()));
            // 设置收件人
            mimeMessage.setRecipients(Message.RecipientType.TO, addresses);
            // 设置邮件主题
            mimeMessage.setSubject(tag);
            // 设置邮件内容
            mimeMessage.setText(message.toString());
            // 发送邮件
            Transport.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("send email error", e);
        }
    }

}